package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.POJO.Setmeal;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.ReportService;
import com.itheima.service.memberService;
import com.itheima.service.setmealService;
import com.itheima.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
   @Reference
   private memberService memberService;
   @Reference
   private setmealService setmealService;
   @Reference
   private ReportService reportService;

    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() throws Exception {
        /*{ "data":
                 {"months":["2019.01","2019.02","2019.03","2019.04"],
                             "memberCount":[3,4,8,10] },
            "flag":true,
            "message":"获取会员统计数据成功"
        }*/
        Calendar calendar = Calendar.getInstance();
        //将时间推移
        calendar.add(Calendar.MONTH,-12); //获取当前日期之前的 12个月
         //把12个月放到 list集合里面
        List<String> arrayList = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH,1);
            arrayList.add(DateUtils.parseDate2String(calendar.getTime(),"yyyy.MM"));
        }
        Map<String,Object> map = new HashMap<>();
        map.put("months",arrayList);

      List<Integer> memberCountList= memberService.findMemberCountByMouth(arrayList);
      map.put("memberCount",memberCountList);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }

    ///report/getSetmealReport.
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        /*
          { "data":
             {"setmealNames":["套餐1","套餐2","套餐3"],
                "setmealCount":[{"name":"套餐1","value":10}, {"name":"套餐2","value":30}, {"name":"套餐3","value":25} ]
                   },
            "flag":true,
            "message":"获取套餐统计数据成功"
             }
             */
        try {
            HashMap<String, Object> map = new HashMap<>();
            List<String> list = new ArrayList<>();
            List<Setmeal> allSetmeal = setmealService.findAllSetmeal();
            for (Setmeal setmeal : allSetmeal) {
                String name = setmeal.getName();
                list.add(name);
            }
            map.put("setmealNames",list);
            Map<String,Integer> setmealCountmap=setmealService.findAllSetmealCount(allSetmeal);
            Set<String> keySet = setmealCountmap.keySet();
            List<Object> objects = new ArrayList<>();
            for (String s : keySet) {
                Map<String, Object> stringObjectMap = new HashMap<>();
                stringObjectMap.put("name",s);
                stringObjectMap.put("value",setmealCountmap.get(s));
                objects.add(stringObjectMap);
            }


            map.put("setmealCount",objects);
            return new Result(true,"套餐统计查询成功",map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"套餐统计查询失败");
        }
    }

/*
{
"data":{    
        "todayVisitsNumber":0,       今日到诊数
        "reportDate":"2019‐04‐25",    日期
        "todayNewMember":0,        新增会员数
        "thisWeekVisitsNumber":0,     本周到诊数
        "thisMonthNewMember":2,     本月新增会员数
        "thisWeekNewMember":0,      本周新增会员数
        "totalMember":10,            总会员数
        "thisMonthOrderNumber":2,      本月预约数
        "thisMonthVisitsNumber":0,    本月到诊数
        "todayOrderNumber":0,        今日预约数
        "thisWeekOrderNumber":0,      本周预约数
        "hotSetmeal":[              热门套餐
                {"proportion":0.4545,"name":"粉红珍爱(女)升级TM12项筛查体检套餐","setmeal_count":5},      
                {"proportion":0.1818,"name":"阳光爸妈升级肿瘤12项筛查体检套餐","setmeal_count":2},      
                {"proportion":0.1818,"name":"珍爱高端升级肿瘤12项筛查","setmeal_count":2},      
                {"proportion":0.0909,"name":"孕前检查套餐","setmeal_count":1}    
        ],  
    },  
"flag":true,  
"message":"获取运营统计数据成功"
}
*/
    ///report/getBusinessReportData.do"
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    @RequestMapping("/getBusinessReportData")
    public  Result getBusinessReportData() throws Exception {
        try {
            Map<String, Object> map = reportService.getBusinessReport();
            return  new Result(true,"获取运营统计数据成功",map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(false,"查询统计错误");
    }


    ///report/exportBusinessReport
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            Map<String, Object> result = reportService.getBusinessReport();
            String reportDate = (String) result.get("reportDate"); //日期
            Integer todayNewMember = (Integer) result.get("todayNewMember");//新增会员数
            Integer totalMember = (Integer) result.get("totalMember");//总会员数
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");//本周新增会员数
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");//thisMonthNewMember
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");//todayOrderNumber
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");//本周预约数
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");//本月预约数
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");//今日到诊数
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");//本周到诊数
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");//本月到诊数
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");//热门套餐

            String filePath = request.getSession().getServletContext().getRealPath("template")+ File.separator+"report_template.xlsx";
            //基于提供的Excel模板文件在内存中创建一个Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for(Map map : hotSetmeal){//热门套餐
                String name = (String) map.get("name");
                Integer setmeal_count = (Integer) map.get("setmeal_count");
                String proportion = (String) map.get("proportion");
                row = sheet.getRow(rowNum ++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion);//占比
            }

            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            excel.write(out);

            out.flush();
            out.close();
            excel.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
    /*
{
"data":{    
        "todayVisitsNumber":0,       今日到诊数
        "reportDate":"2019‐04‐25",    日期
        "todayNewMember":0,        新增会员数
        "thisWeekVisitsNumber":0,     本周到诊数
        "thisMonthNewMember":2,     本月新增会员数
        "thisWeekNewMember":0,      本周新增会员数
        "totalMember":10,            总会员数
        "thisMonthOrderNumber":2,      本月预约数
        "thisMonthVisitsNumber":0,    本月到诊数
        "todayOrderNumber":0,        今日预约数
        "thisWeekOrderNumber":0,      本周预约数
        "hotSetmeal":[              热门套餐
                {"proportion":0.4545,"name":"粉红珍爱(女)升级TM12项筛查体检套餐","setmeal_count":5},      
                {"proportion":0.1818,"name":"阳光爸妈升级肿瘤12项筛查体检套餐","setmeal_count":2},      
                {"proportion":0.1818,"name":"珍爱高端升级肿瘤12项筛查","setmeal_count":2},      
                {"proportion":0.0909,"name":"孕前检查套餐","setmeal_count":1}    
        ],  
    },  
"flag":true,  
"message":"获取运营统计数据成功"
}
*/

    public static void main(String[] args) throws Exception {

        Calendar calendar = Calendar.getInstance();
        //将时间推移
        int i = calendar.get(Calendar.DAY_OF_WEEK);
        System.out.println(i);
        i=i-1;
        calendar.add(Calendar.DATE,-(i-1));
        System.out.println(calendar.getTime());
        calendar.add(Calendar.DATE,+6);
        System.out.println(calendar.getTime());
      /* String a="19988.2";
        String replace = a.replace(".", "-");
        System.out.println(replace);*/
    }
}
